<template>
  <div class="cart-container">
    <Headbar />
    <HeadCartBrand :title="title" />
    <!-- 购物车有内容 -->
    <div ref="elem">
      <div class="cart-content yh-layout-box" v-if="cartList.length">
        <div class="cart-list-theader">
          <div class="col-list col-check">
            <el-checkbox v-model="checkedAll" @change="handleCheckedAll()">全选</el-checkbox>
          </div>
          <div class="col-list col-product">商品</div>
          <div class="col-list col-specification">规格</div>
          <div class="col-list col-price">价格</div>
          <div class="col-list col-amount">数量</div>
          <div class="col-list col-count">小计</div>
          <div class="col-list col-operate">操作</div>
        </div>
        <div class="store-wrap">
          <div class="store-cart-content">
            <div class="store-list" v-for="(item, index) in cartList">
              <div class="store-company">
                <el-checkbox v-model="item.checked" @change="handleCheckedItem(index)"></el-checkbox>
                <i @click="routeToPath('/factory?factoryId='+item.factoryId)">{{ item.factoryName }}</i>
                <img src="../../assets/images/cart/cart_01.png" class="chat-img" @click="handleChat()">
                <span v-if="item.isFactory == 0">已失效</span>
              </div>
              <div class="store-ul"> <!-- store-pdList-active -->
                <div class="store-pdList" :class="{'store-pdList-active': panel.checked, 'fail': item.isFactory == 0 || panel.productStatusInfo!='', 'store-pdList-one': item.cartItemDTOList.length == 1}" v-for="(panel, j) in item.cartItemDTOList">
                  <div class="store-pd-msg">
                    <div class="store-check fl check_pd_msg">
                      <el-checkbox v-model="panel.checked" @change="handleCheckedPanel(item)"></el-checkbox>
                    </div>
                    <div class="checked-pdPic fl check_pd_msg" @click="routeToPath('/product/detail?id='+panel.productId)">
                      <img :src="URL.PIC + panel.productPic" alt="panel.productName" />
                    </div>
                    <div class="checked-pdName fl check_pd_msg" @click="routeToPath('/product/detail?id='+panel.productId)">
                      {{ panel.productName }}
                    </div>
                    <div class="checked-specification fl check_pd_msg">{{ panel.productSpec }}</div>
                    <div class="checked-price fl check_pd_msg">￥{{ panel.productPrice }}</div>
                    <div class="checked-count fl check_pd_msg">
                      <el-input-number v-model="panel.quantity" :min="1" @change="handleChangeNum(item.factoryId, panel.id, panel.quantity)" v-if="panel.productStatusInfo==''"></el-input-number>
                      <div class="inventory_error inError" v-if="panel.productInventoryInfo!='' && panel.productStatusInfo==''" @click="handleInventory()">
                        <img src="../../assets/images/cart/cart_03.png"/>
                        {{ panel.productInventoryInfo }}
                      </div>
                      <div class="inventory_error" v-if="panel.productStatusInfo!=''">{{ panel.productStatusInfo }}</div>

                    </div>
                    <div class="checked-subtotal fl check_pd_msg">￥{{ (panel.productPrice * panel.quantity).toFixed(2) }}</div>
                    <div class="checked-operate fl check_pd_msg">
                      <div class="delate-btn" @click="handleDel(panel.id)">删除</div>
                      <!-- <div class="moveCollect" @click="handleMoveFavorites(panel.id)">移入收藏夹</div> -->
                    </div>
                  </div>
                </div>
              </div>

            </div>
          </div>
          <!-- <div class="store-fail">
            <h3 class="fail-title">失效商品：</h3>
            <div class="store-list">
              <div class="store-company">
                <el-checkbox v-model="checked">
                   威力狮品牌广州专卖店
                  <img src="../../assets/images/cart/cart_01.png" class="chat-img">
                </el-checkbox>
                <span class="store-state fr">维护中</span>
              </div>
              <div class="store-ul">
                <div class="store-pdList">
                  <div class="store-pd-msg">
                    <div class="store-check fl check_pd_msg">
                      <el-checkbox v-model="checked"></el-checkbox>
                    </div>
                    <div class="checked-pdPic fl check_pd_msg">
                      <img src="../../assets/images/cart/cart_02.png"/>
                    </div>
                    <div class="checked-pdName fl check_pd_msg">
                      施耐德 插拔式中间继电器 2副触点,5A, 指示灯,24VDC；RXM2LB2BD
                    </div>
                    <div class="checked-specification fl check_pd_msg ml-10">黑色长盒10cm</div>
                    <div class="checked-price fl check_pd_msg ml-10"></div>
                    <div class="checked-count fl check_pd_msg ml-10">
                      商品已下架
                    </div>
                    <div class="checked-subtotal fl check_pd_msg ml-10"></div>
                    <div class="checked-operate fl check_pd_msg ml-10">
                      <div class="delate-btn">删除</div>
                      <div class="moveCollect">移入收藏夹</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div> -->
          <div class="settlement-bar" ref="bar">
            <div class="settlement-fl-op fl">
              <el-checkbox v-model="checkedAll" @change="handleCheckedAll()">全选</el-checkbox>
              <span class="delete-pds" @click="handleDelMore()">删除选中商品</span>
              <!-- <span class="move-pds" @click="handleMoveFavoritesMore()">移入收藏夹</span> -->
            </div>
            <div class="settlement-fr-op fr">
              <span class="choose-pds">已选 {{ checkTotalNum }} 件商品</span>
              <span class="column-total">合计：<span class="sum_price">￥{{ checkTotalPrice }}</span>（不含运费）</span>
              <span class="settlement_btn fr" @click="handleConfirm()">结算</span>
            </div>
          </div>
          <div class="isFixed" :class="orderBarFixed == true ? 'show' :''">
            <div class="settlement-bar">
              <div class="settlement-fl-op fl">
                <el-checkbox v-model="checkedAll" @change="handleCheckedAll()">全选</el-checkbox>
                <span class="delete-pds" @click="handleDelMore()">删除选中商品</span>
                <!-- <span class="move-pds" @click="handleMoveFavoritesMore()">移入收藏夹</span> -->
              </div>
              <div class="settlement-fr-op fr">
                <span class="choose-pds">已选 {{ checkTotalNum }} 件商品</span>
                <span class="column-total">合计：<span class="sum_price">￥{{ checkTotalPrice }}</span>（不含运费）</span>
                <span class="settlement_btn fr" @click="handleConfirm()">结算</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 购物车有内容 -->

    <!-- 暂无内容已登录时 -->
    <div class="cart-null" v-if="!cartList.length && empty">
      <div class="cart-ioc">
        <img src="@/assets/images/cart/cart-empty-140x140.png" />
      </div>
      <div class="cart-text">
        <p class="null_tips">购物车空空的哦~，去看看心仪的商品吧~</p>
        <div class="button-item">
          <router-link :to="{path: '/'}" class="go_shopping">去购物></router-link>
        </div>
      </div>
    </div>
    <!-- 暂无内容已登录时 -->
    <LikeItem />
    <Footbars />
  </div>
</template>

<script>
import Headbar from '@/components/Layouts/Headbar'
import HeadCartBrand from '@/components/Layouts/HeadCartBrand'
import Footbars from '@/components/Layouts/Footbars'
import LikeItem from '@/components/Business/LikeItem'

import { getCartList, deleteCart, deleteCartList, updateCartNum } from '@/api/cart'
export default {
  name: 'CartList',
  components: {
    Headbar,
    HeadCartBrand,
    Footbars,
    LikeItem
  },
  data() {
    return {
      title: '进货车',
      cartList: [], //购物车列表
      checkedAll: false, //全选
      checkTotalPrice: '0.00', //已选总价
      checkTotalNum: '0', //已选件数
      againIds: this.getUrlParams('againIds'),//再次购买参数
      empty: false,
      orderBarFixed: false, //计算是否固定结算条
      windowHeight: 0, //浏览器高度
      orderHeight: 0, //订单列表高度
      orderOffsetTop: 0 //结算距离顶部距离
    }
  },
  created() {
    this.getCartList();
    //this.getTotalPrice();

  },
  mounted () {
    this.windowHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; //浏览器高度
    window.addEventListener('scroll', this.handleScroll)
  },
  methods: {
    handleScroll() {
      let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
      let offsetTop = this.orderOffsetTop - this.windowHeight + 62
      scrollTop < offsetTop ? this.orderBarFixed = true : this.orderBarFixed = false
    },
    handleChat() {
      this.$message({
        message: '供应商暂未开启客服功能',
        type: 'warning'
      });
    },
    //获取购物车列表
    getCartList() {
      getCartList().then(res => {
        if(res.code == 200){
          this.cartList = res.data;
          this.$nextTick(()=>{
            this.orderHeight = this.$refs.elem.offsetHeight;
            this.orderOffsetTop = this.$refs.bar.offsetTop;
            //147头部高度 62结算栏高度 85 = 147 - 62
            if(this.orderHeight>=this.windowHeight-85){
              this.orderBarFixed = true
            }
          })

          if(!res.data.length){
            this.empty = true
          }
          //再次购买
          if(this.againIds != ''){
            this.againBuyOrder();
          }
          this.getTotalPrice();
          console.log(this.cartList)
        }
      })
    },
    //改变数量
    handleChangeNum(pid, id, value) {
      if(value == undefined){
        this.$message({
          type: 'error',
          message: '请输入购买数量'
        });
        return;
      }
      console.log(value)
      this.updateCartNum(id, value);
      this.getTotalPrice();
    },
    //更新数量
    updateCartNum(cartId, quantity) {
      const params = {
        cartId: cartId,
        quantity: quantity
      }
      updateCartNum(params).then(res => {
        console.log(res)
        if(res.code != 200){
          this.$message({
            type: 'error',
            message: res.msg
          });
        }
      })
    },
    //获取已选总价、总数量
    getTotalPrice() {
      let checkTotalPrice = 0;
      let checkTotalNum = 0;
      let checkedAll = 0;
      this.cartList.forEach((item, i) => {
        item.cartItemDTOList.forEach((panel, j) => {
          if(panel.checked != undefined && panel.checked){
            checkTotalPrice += parseInt(panel.quantity) * panel.productPrice;
            checkTotalNum += parseInt(panel.quantity);
          }
        });
        if(item.checked){
          checkedAll ++;
        }
      });
      this.checkTotalPrice = checkTotalPrice.toFixed(2);
      this.checkTotalNum = checkTotalNum;
      this.checkedAll = (checkedAll == this.cartList.length) ? true : false;
    },
    //选择云工厂
    handleCheckedItem(index) {
      let item = this.cartList[index];
      item.checked = item.checked ? true : false;
      this.cartList[index].cartItemDTOList.forEach((panel, i) => {
        panel.checked = item.checked ? true : false;
      });
      this.getTotalPrice();
    },
    //选择商品
    handleCheckedPanel(data) {
      this.cartList.forEach((item, i) => {
        if(item.factoryId == data.factoryId){
          let checkProductLen = 0;
          item.cartItemDTOList.forEach((panel, j) => {
            if(panel.checked){
              checkProductLen ++;
            }
          })
          item.checked = (item.cartItemDTOList.length == checkProductLen) ? true : false;
        }
      })
      this.getTotalPrice();
    },
    //全选
    handleCheckedAll() {
      this.cartList.forEach((item, i) => {
        item.checked = this.checkedAll ? true : false;
        item.cartItemDTOList.forEach((panel, j) => {
          panel.checked = this.checkedAll ? true : false;
        })
      })
     this.getTotalPrice();
    },
    //获取选中商品ids
    getCheckedIds() {
      let ids = '';
      this.cartList.forEach((item, i) => {
        item.cartItemDTOList.forEach((panel, j) => {
          if(panel.checked){
            ids += panel.id + ','
          }
        })
      })
      return ids = ids.substring(0, ids.length-1);
    },
    //删除单个进货车
    deleteCart(id) {
      const params = {
        cartId: id
      }
      deleteCart(params).then(res => {
        if(res.code == 200){
          this.$message({
            type: 'success',
            message: '删除成功'
          });
          this.getCartList();
        }else{
          this.$message({
            type: 'error',
            message: res.msg
          });
        }
      })
    },
    //删除批量进货车
    deleteCartList() {
      const params = {
        ids: this.getCheckedIds()
      }
      deleteCartList(params).then(res => {
        if(res.code == 200){
          this.$message({
            type: 'success',
            message: '删除成功'
          });
          this.getCartList();
        }else{
          this.$message({
            type: 'error',
            message: res.msg
          });
        }
      })
    },
    //删除单个进货车
    handleDel(id) {
      this.$confirm('是否确认删除商品？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        this.deleteCart(id);
      }).catch(() => {

      });
    },
    //删除批量进货车
    handleDelMore() {
      if(this.getCheckedIds() == ''){
        this.$message({
          type: 'success',
          message: '请选择需要删除的商品'
        });
        return;
      }
      this.$confirm('是否确认删除商品？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        this.deleteCartList()
      }).catch(() => {

      });
    },
    //结算
    handleConfirm() {
      const ids = this.getCheckedIds()
      if( ids== ''){
        this.$message('还没有选择商品哦');
        return;
      }
      location.href = this.URL.mall+'/cart/confirmOrder?ids='+ids
      // this.$router.push({
      //   name: 'ConfirmOrder',
      //   query: {
      //     ids: ids
      //   }
      // })
    },
    //再次购买
    againBuyOrder() {
      let checkProductLen = 0;
      let againIdsArr = []
      if(this.againIds!=''){
        againIdsArr = this.againIds.split(',')
      }
      this.cartList.forEach((item, i) => {
        item.cartItemDTOList.forEach((panel, j) => {
          againIdsArr.forEach((group, n) => {
            if(group == panel.id){
              panel.checked = true;
              checkProductLen ++;
              item.checked = (item.cartItemDTOList.length == checkProductLen) ? true : false;
            }
          })
        })
      })
    },
    //移入单个收藏夹
    // handleMoveFavorites(id) {
    //   this.$confirm('<h4 class="title-move-favorites">是否移入收藏夹？</h4>移入后选中商品将不在进货车中显示', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     dangerouslyUseHTMLString: true
    //   }).then(() => {
    //     this.$message({
    //       type: 'success',
    //       message: '收藏成功'
    //     });
    //   }).catch(() => {

    //   });
    // },
    //移除多个收藏夹
    // handleMoveFavoritesMore() {
    //   console.log(this.getCheckedIds())
    //   this.$confirm('<h4 class="title-move-favorites">是否移入收藏夹？</h4>移入后选中商品将不在进货车中显示', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     dangerouslyUseHTMLString: true
    //   }).then(() => {
    //     this.$message({
    //       type: 'success',
    //       message: '收藏成功'
    //     });
    //   }).catch(() => {

    //   });
    // },
    //库存不足提示语
    handleInventory() {
      this.$confirm('因可能存在系统缓存、页面更新导致商品数量库存更新不及时等不确定性情况出现，商品可售数量以确认订单页为准。选择数量超出库存时，请重新调整购买数量。<br/><br/>如有疑问，请联系商家确认库存。', '库存说明', {
        showCancelButton: false,
        showConfirmButton: false,
        dangerouslyUseHTMLString: true
      }).then(() => {

      }).catch(() => {

      });
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/pages/cart.scss';

</style>
<style lang="scss">
.cart-container{
  .el-input-number{
    width: 80px;
    line-height: 25px;
    // margin-bottom: 10px;
  }
  .el-input-number .el-input__inner{
    padding: 0 25px;
  }
  .el-input-number__decrease, .el-input-number__increase{
    width: 25px;
  }
  .el-input__inner{
    line-height: 25px;
    height: 27px;
  }
  .title-move-favorites{
    margin: 0 0 10px;
    font-size: 16px;
  }
  .cart-content{
    .el-checkbox__input.is-checked+.el-checkbox__label{
      color: #255b8b;
    }
  }
}
.cart-content .store-wrap .isFixed{
  position: fixed;
  width: 100%;
  height: 60px;
  left: 0;
  bottom: 0;
  z-index: 66;
  margin-bottom: 0;
  border: none;
  box-shadow: 0 -1px 8px rgba(0,1,1,.08);
  background: #fff;
  display: none;
  &.show{
    display: block;
  }
  .settlement-bar{
    border: none;
  }
}
</style>
